// 本地数据存储工具

// 初始化数据
export const initData = () => {
  if (!localStorage.getItem('categories')) {
    const categories = [
      { id: 1, name: '安全教育', description: '新生入学安全知识', sort_order: 1 },
      { id: 2, name: '校园常识', description: '学校基本信息和规章制度', sort_order: 2 },
      { id: 3, name: '学习指导', description: '学习方法和技巧', sort_order: 3 },
      { id: 4, name: '生活指南', description: '校园生活相关知识', sort_order: 4 }
    ]
    saveLocalData('categories', categories)
  }

  if (!localStorage.getItem('questions')) {
    const questions = [
      {
        id: 1,
        category_id: 1,
        type: 'judge',
        question_text: '在宿舍内使用大功率电器是安全的。',
        options: null,
        correct_answer: 'B'
      },
      {
        id: 2,
        category_id: 1,
        type: 'multiple',
        question_text: '遇到火灾时，正确的做法包括：',
        options: [
          { label: 'A', value: '立即拨打119' },
          { label: 'B', value: '用湿毛巾捂住口鼻' },
          { label: 'C', value: '乘坐电梯逃生' },
          { label: 'D', value: '大声呼救' }
        ],
        correct_answer: 'A,B,D'
      },
      {
        id: 3,
        category_id: 2,
        type: 'single',
        question_text: '学校图书馆开放时间是？',
        options: [
          { label: 'A', value: '8:00-22:00' },
          { label: 'B', value: '9:00-21:00' },
          { label: 'C', value: '7:00-23:00' },
          { label: 'D', value: '全天24小时' }
        ],
        correct_answer: 'A'
      }
    ]
    saveLocalData('questions', questions)
  }

  if (!localStorage.getItem('users')) {
    const users = [
      {
        id: 3,
        realName: '李中悦',
        studentNo: '0001',
        college: '计算机学院',
        major: '软件工程',
        status: 1
      },
      {
        id: 4,
        realName: '王小明',
        studentNo: '0002',
        college: '信息学院',
        major: '信息管理',
        status: 1
      }
    ]
    saveLocalData('users', users)
  }

  if (!localStorage.getItem('records')) {
    const records = [
      {
        id: 1,
        user_id: 3,
        score: 85,
        is_passed: 1,
        submit_time: '2024-01-15 14:30:00'
      },
      {
        id: 2,
        user_id: 4,
        score: 92,
        is_passed: 1,
        submit_time: '2024-01-15 15:20:00'
      }
    ]
    saveLocalData('records', records)
  }
}

// 获取本地数据
export const getLocalData = (key) => {
  const data = localStorage.getItem(key)
  return data ? JSON.parse(data) : []
}

// 保存本地数据
export const saveLocalData = (key, data) => {
  localStorage.setItem(key, JSON.stringify(data))
}

// 清空所有数据
export const clearAllData = () => {
  const keys = ['categories', 'questions', 'users', 'records']
  keys.forEach((key) => localStorage.removeItem(key))
}

